#!/usr/bin python3
# -*- coding:UTF-8 -*-
# Author: zxx
from paddleocr import PaddleOCR
import re
from PIL import Image
import pandas as pd
import sys
import json

def invoice_ocr(path):

    result = PaddleOCR().ocr(path)
    inform = []
    result = result[0]

    for line in result:
        inform.append(line[1][0])
    # print(inform)
    String2 = '【' + '】【'.join(inform) + '】'
    # print(String2)
    if '发' not in String2 and '票' not in String2:
        print('no')
        im = Image.open(path)
        out = im.transpose(Image.ROTATE_180)
        out.save(path)
        result = PaddleOCR().ocr(path)
        inform = []
        for line in result:
            inform.append(line[1][0])
        String2 = '【' + '】【'.join(inform) + '】'
    #    print('yes')
    #else:

    # 正则规则

    code_regular = r'(\d{10}(04|05|11|12)|144\d{7}10|\d{7}(6|3)\d{2})】' #发票代码 (?:(?<!\d)\d{12}(?!\d))
    number_regular = r'(?<!\d)(\d{8})】' #发票号码 (?:(?<!\d)\d{8}(?!\d))
    judge_regular = r'校验码[:：](\d+)】' #校验码 (?:校验码:|校验码：)[0-9]{1,20}
    ymd_regular = r'\d{4}年\d{2}月\d{2}日' #发票日期 [0-9]{1,4}年[0-9]{1,2}月[0-9]{1,2}
    amounts_regular = r'(?:￥|¥)?((?:[1-9]\d{0,9}|0)\.\d{2})】' #发票金额
    tax_regular = r'【(\d{1,2}%)】' #税率
    name_regular = r'称[:：](.*?)】' # 购买方/销售方 (?:称:|称：)[\u4e00-\u9fa5]+
    taxpayer_number_regular = r'纳税人识别号[:：](\w+)】' # 纳税人识别号 (?:纳税人识别号:|纳税人识别号：)\w+

    number = invoice_field(String2,number_regular) # 发票号码
    code = invoice_field(String2,code_regular) # 发票代码
    judge = invoice_field(String2,judge_regular) # 校验码
    ymd = invoice_field(String2,ymd_regular) # 开票日期
    tax = invoice_field(String2,tax_regular) # 税率
    purch_name = invoice_field(String2,name_regular,1) # 购买方名称
    sale_name = invoice_field(String2,name_regular,2) # 销售方名称
    purch_id = invoice_field(String2,taxpayer_number_regular,1) # 购买方纳税人识别号
    sale_id = invoice_field(String2,taxpayer_number_regular,2) # 销售方纳税人识别号

    invoice2 = re.sub('[a-zA-Z]','',String2)
    # 发票金额
    try:
        amounts = re.findall(amounts_regular,invoice2)
        amounts = [float(i) for i in amounts]
        amounts.sort()
        amount = amounts[-2]
        total_price = amounts[-1]
    except:
        amount = '--'
        total_price = '--'


    # info = {
    #     '路径':path,
    #     '发票代码':code,
    #     '发票号码':number,
    #     '校验码':judge,
    #     '日期':ymd,
    #     '总金额':total_price,
    #     '销售金额':amount,
    #     '税率':tax,
    #     '购买方':purch_name,
    #     '购买方纳税人识别号':purch_id,
    #     '销售方':sale_name,
    #     '销售人纳税人识别号':sale_id,
    #  }
    info = {
        'path':path,
        'invoice_code':code,
        'invoice_num':number,
        'check_code':judge,
        'invoice_date':ymd,
        'total_amount':total_price,
        'amount':amount,
        'commodity_tax_rate':tax,
        'purchaser_name':purch_name,
        'purchaser_register_num':purch_id,
        'seller_name':sale_name,
        'seller_register_num':sale_id,
        'string':String2
     }

    # df = pd.DataFrame(info,columns=['路径','购买方','购买方纳税人识别号','销售方','销售人纳税人识别号','发票代码','发票号','校验码','日期','总金额','销售金额','税率'])
    return info

def invoice_field(string ,regular , index = 1):
    try:
        value = re.findall(regular,string)[index-1]
    except:
        value = ''
    return value




if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit(1)

    # path = './img/test.png'
    result = invoice_ocr(sys.argv[1])
    #return result
    print(json.dumps(result))
